﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;
using System.Web;
using System.Drawing;
using System.Threading;

namespace Allocine_Lib
{
    public static class Allocine
    {

        /// <summary>
        /// Used this method to check the connectivity to Internet.
        /// </summary>
        /// <param name="url">Url sed to check the connection.</param>
        /// <returns>True if connected. False otherwise.</returns>
        private static bool NetworkConnectionIsOk(string url)
        {
            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                //Proxy
                WebProxy wProxy = new WebProxy("10.126.71.12", 80);
                wProxy.Credentials = new NetworkCredential("rfraftp", "Siberbo2000", "fr");
                myHttpWebRequest.Proxy = wProxy;
                //Proxy

                using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse())
                {
                    if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }

            }
            catch (Exception e)
            {
                return false;
                //throw new Exception("Error while checking Internet connection. Are you sure you are connected ? Error: " + e.Message);
            }
        }

        public static Film GetFilmDetails(string idAllocine)
        {
            Film MonFilm = new Film();
            string s = GetSourceHTML("http://www.allocine.fr/film/fichefilm_gen_cfilm=" + idAllocine + ".html");



            s = Regex.Replace(s, "[\r\n]", "");

            MonFilm.ID = idAllocine;
            MonFilm.Titre = removeUnwantedChars(Regex.Match(s, "<h1[^>]*>(.*?)</h1>").ToString());
            MonFilm.TitreOriginal = removeUnwantedChars(Regex.Match(s, "<h4>Titre original : <i>(.*?)</i>").Groups[1].ToString());

            MonFilm.DureeChaine = removeUnwantedChars(Regex.Match(s, "<h4>Durée : (.*?)</h4>").Groups[1].ToString());
            
            MonFilm.Annee = removeUnwantedChars(Regex.Match(s, "Année de production : (\\d{4})").Groups[1].ToString());
            MonFilm.Realisateurs = removeUnwantedChars(Regex.Match(s, "Réalisé par(.*?)</h4>").Groups[1].ToString()).Replace(", ", ",").Split(',');
            MonFilm.Acteurs = removeUnwantedChars(Regex.Match(s, "<h4>Avec(.*?)</h4>").Groups[1].ToString()).Replace(", ", ",").Split(',');
            MonFilm.Genre = removeUnwantedChars(Regex.Match(s, "Genre :(.*?)</h4>").Groups[1].ToString()).Replace(", ", ",").Split(',');


            //Note Presse
            string sNotePresse = removeUnwantedChars(Regex.Match(s, "Presse.*?class=['\"]etoile_(\\d)['\"]").Groups[1].ToString());
            try
            {
                MonFilm.NotePresse = (float)(System.Double.Parse(sNotePresse) * 2.5);
            }
            catch { }

            //Note Spectateurs
            string sNoteSpectateur = removeUnwantedChars(Regex.Match(s, "Spectateurs.*?class=['\"]etoile_(\\d)['\"]").Groups[1].ToString());
            try
            {
                MonFilm.NoteSpectateurs = (float)(System.Double.Parse(sNotePresse) * 2.5);
            }
            catch { }

            MonFilm.Synopsis = removeUnwantedChars(Regex.Match(s, "Synopsis(.*?)</h4></div>").Groups[1].ToString());

            //Jaquette

            //Meediofr FR
            // if (NetworkConnectionIsOk(@"http://www.meediofr.org/~dmdocuments/FR/" + MonFilm.ID + "_FR.png"))
            //{
            //    MonFilm.URLImage = @"http://www.meediofr.org/~dmdocuments/FR/" + MonFilm.ID + "_FR.png";
            MonFilm.LoadImage(@"http://www.meediofr.org/~dmdocuments/FR/" + MonFilm.ID + "_FR.png");    
            goto BandeAnnonce;
            //}

             //Meediofr US
             //if (NetworkConnectionIsOk(@"http://www.meediofr.org/~dmdocuments/US/" + MonFilm.ID + "_US.png"))
             //{
             //    MonFilm.URLImage = @"http://www.meediofr.org/~dmdocuments/US/" + MonFilm.ID + "_US.png";
             //    goto BandeAnnonce;
             //}

            //Allocine
            //string strThumbURL = Regex.Match(s, "/film/galerievignette_gen_cfilm=.+?html").ToString();
            //if (strThumbURL != "")
            //{
            //    strThumbURL = "http://www.allocine.fr" + strThumbURL;
            //    string strBodyThumb = GetSourceHTML(strThumbURL);
            //    if (strBodyThumb != null && strBodyThumb != "")
            //    {
            //        strBodyThumb = Regex.Replace(strBodyThumb, "[\r\n]", "");
            //        strThumbURL = removeUnwantedChars(Regex.Match(strBodyThumb, "id=['\"]imgNormal['\"] class=['\"]photo['\"] src=['\"](.*?)['\"]").Groups[1].ToString());

            //        MonFilm.URLImage = strThumbURL;
            //    }
            //}

            BandeAnnonce:


            //BA
            //string strBAURL = @"http://allocine.msn.fr/video/video_gen_cfilm=" + idAllocine + ".html";
            //if (strBAURL != "")
            //{
            //    string strBodyBA = GetSourceHTML(strBAURL);
            //    if (strBodyBA != null && strBodyBA != "")
            //    {
            //        foreach (string ligne in strBodyBA.Split((char)13))
            //        {

            //            if (ligne.Contains("AC_AX_RunContent"))
            //            {
            //                //Console.WriteLine(ligne);
            //                string[] decompose = ligne.Split("'".ToCharArray());
            //                string Lien = "http://allocine.msn.fr" + decompose[decompose.GetUpperBound(0) - 1];
            //                //Console.WriteLine("Telechargement de : " + Lien);
            //                strBodyBA = GetSourceHTML(Lien); ;
            //                foreach (string ligne2 in strBodyBA.Split((char)13))
            //                {
            //                    if (ligne2.Contains("mms://"))
            //                    {
            //                        int posdeb = ligne2.IndexOf("mms://");
            //                        int posfin = ligne2.IndexOf(".wmv");
            //                        Lien = ligne2.Substring(posdeb, posfin - posdeb + 4);
            //                        Lien = @"http://" + Lien.Substring(Lien.ToLower().IndexOf("mediaplayer.allocine.fr"));
            //                        MonFilm.URLBandeAnnonce = Lien;

                                   
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}

            return MonFilm;
        }

        static string removeUnwantedChars(string tInput)
        {
            tInput = Regex.Replace(tInput, "<[^<]*>", "");
            tInput = Regex.Replace(tInput, "Plus.*?...", "");
            tInput = tInput.Replace("\\s{2,}", " ");
            tInput = tInput.Replace("&nbsp;", "").Trim();
            return tInput;
        }

 

        /// <summary>
        /// Télécharge la page des salles de cinéma sur allocine.fr.
        /// </summary>
        
        public static List<Salle> GetSalles(string NomSalle)
        {
            List<Salle> ListeSalle = new List<Salle>();

            //Recupère le resultats des salles
            string s;
            string Separateur = @"<a href=""/seance/salle_gen_csalle=";
            s = GetSourceHTML("http://www.allocine.fr/recherche/?motcle=" + NomSalle + "&rub=3");
            if (s.Contains("<b>Cinémas <h4>("))
            {
                foreach (string _ligneSalle in Regex.Split(s, Separateur))
                {
                    if (_ligneSalle.StartsWith("P"))
                    {
                        Salle MaSalle = new Salle();
                        Regex myRegex = new Regex(@"(.*).html.*>(.*)-(.*),(.*).*");
                         
                        string s2 = removeUnwantedChars(_ligneSalle);
                        Match m = myRegex.Match(s2);
                        if (m.Success)
                        {
                            MaSalle.SalleId = m.Groups[1].Value.Trim();
                            MaSalle.NomSalle = m.Groups[2].Value.Trim();
                            MaSalle.CP = m.Groups[3].Value.Trim();
                            MaSalle.Ville = m.Groups[4].Value.Trim();
                            MaSalle.Lien = "http://www.allocine.fr/seance/salle_gen_csalle=" + MaSalle.SalleId + ".html";
                            ListeSalle.Add(MaSalle);

                        }

                    }
                }
            }

            ListeSalle.Sort(new SalleComparer());

            return ListeSalle;

        }

        public static Films RechercheFilm(string TitreFilm)
        {
            //List<Film> ListeFilm = new List<Film>();
            Films ListeFilm = new Films();

            //Recupère le resultats des films

            string strURL = "http://www.allocine.fr/recherche/?motcle=" + HttpUtility.UrlEncode(TitreFilm, Encoding.Default) + "&rub=1";
            int _NbrFilms;
            int _NbrPages;

            string strBody = GetSourceHTML(strURL);

            _NbrFilms = Convert.ToInt32(Regex.Match(strBody, @".*Films <h4>\((.*) réponse").Groups[1].ToString());
            _NbrPages = _NbrFilms / 20;

            for (int i = 1; i <= _NbrPages+1; i++)
            {
                strURL = "http://www.allocine.fr/recherche/default.html?motcle=" + HttpUtility.UrlEncode(TitreFilm, Encoding.Default) + "&rub=1&page=" + i.ToString();
                strBody = GetSourceHTML(strURL);
                MatchCollection myMatches = Regex.Matches(strBody, "<a href=\"/film/fichefilm_gen_cfilm=\\d{4,6}.html\">.*?</table>");

                foreach (Match movieCode in myMatches)
                {
                    Film MonFilm = new Film();

                    string strMovieCode = movieCode.ToString();


                    string strLink = Regex.Match(strMovieCode, "/film/fichefilm_gen_cfilm=\\d{4,6}.html").ToString();
                    strLink = "http://www.allocine.fr" + strLink;
                    MonFilm.ID = removeUnwantedChars(Regex.Match(strLink, ".*?cfilm=(.*?).html").Groups[1].ToString());
                    string URLThumbnail = Regex.Match(strMovieCode, @".*src=""(.*gif|.*jpg)"".*").Groups[1].ToString();
                    if (URLThumbnail.Contains("empty") == false)
                    {
                        MonFilm.LoadThumbnail(URLThumbnail);
                    }
                    //Meediofr FR
                    //if (NetworkConnectionIsOk(@"http://www.meediofr.org/~dmdocuments/FR/" + MonFilm.ID + "_FR.png"))
                    //{
                        MonFilm.LoadImage(@"http://www.meediofr.org/~dmdocuments/FR/" + MonFilm.ID + "_FR.png");
                        //goto BandeAnnonce;
                    //}
                    MonFilm.Titre = removeUnwantedChars(Regex.Match(strMovieCode, "<h4>.*?</h4>").ToString());
                    MonFilm.TitreOriginal = removeUnwantedChars(Regex.Match(strMovieCode, "<h5>.*?</h5>").ToString());
                    MonFilm.Annee = removeUnwantedChars(Regex.Match(strMovieCode, ">(\\d{4})<").Groups[1].ToString());
                    ListeFilm.Add(MonFilm);

                }
            }

            
            
            //ListeFilm.Sort(new FilmComparer());

            return ListeFilm;

        }

       


        private static string GetSourceHTML(string url)
        {
            string sourceHTML = string.Empty;

            try
            {

                WebClient m_webClient = new WebClient();

                //Proxy
                WebProxy wProxy = new WebProxy("10.126.71.12", 80);
                wProxy.Credentials = new NetworkCredential("rfraftp", "Siberbo2000", "fr");
                m_webClient.Proxy = wProxy;
                //Proxy

                //m_webClient.Encoding = Encoding.UTF8;
                sourceHTML = m_webClient.DownloadString(url);

            }
            catch (Exception e)
            {
                throw new Exception("An exception occured when you tried to download the file: " + e.Message);
            }

            return sourceHTML;

        }


        /// <summary>
        /// Method used to extract the content of a string from a 2 strings.
        /// </summary>
        private static string GetStringBetweenTwoStrings(string src, string start, string end)
        {
            string retVal = string.Empty;

            int idxStart = src.IndexOf(start);

            if (idxStart != -1)
            {
                idxStart++;

                int idxEnd = src.IndexOf(end, idxStart);

                if (idxEnd != -1)
                {
                    retVal = src.Substring(idxStart, idxEnd - idxStart);
                }
            }

            return retVal;
        }
    }


 

}
